#include <webx/menu.h>
#include <dbentity/T_XG_GROUP.h>

class GetUserMenuList : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(GetUserMenuList)

int GetUserMenuList::process()
{
	int res;
	string sqlcmd;
	string grouplist;
	set<string> menus;
	set<MenuItem> menuset;
	set<GroupItem> groupset;
	sp<DBConnect> dbconn = webx::GetDBConnect();

	if (webx::GetMenuSet(menuset) < 0)
	{
		LogTrace(eERR, "get menu set failed");

		return simpleResponse(XG_SYSERR);
	}

	if (webx::GetGroupSet(groupset) < 0)
	{
		LogTrace(eERR, "get group set failed");

		return simpleResponse(XG_SYSERR);
	}
	
	try
	{
		checkLogin();

		grouplist = session->get("GROUPLIST");

		json["login"] = (int)(1);
	}
	catch(Exception e)
	{
		json["login"] = (int)(0);
	}

	GroupItem grp;
	vector<string> vec;
	vector<MenuItem> ms;

	if (grouplist == "system" || grouplist == "header" || grouplist == "footer")
	{
		vec.push_back(grouplist);
	}
	else
	{
		stdx::split(vec, grouplist, ",");

		vec.push_back("public");
	}

	string client = request->getHeadValue("User-Agent");
	
	stdx::tolower(client);

	if (client.find("android") == string::npos && client.find("iphone") == string::npos && client.find("ipad") == string::npos)
	{
		client = "P";
	}
	else
	{
		client = "M";
	}
	
	res = 0;

	for (auto& m : vec)
	{
		if ((grp.id = m).length() > 0)
		{
			MenuItem menu;
			auto it = groupset.find(grp);
			
			if (it == groupset.end()) continue;
			
			for (auto& n : it->menus)
			{
				if ((menu.id = n).length() > 0)
				{
					int num = 0;
					auto it = menuset.find(menu);
					
					if (it == menuset.end()) continue;

					if (it->title.length() > 0)
					{
						menu.folder = it->folder;

						for (auto& item : menuset)
						{
							if (item.folder == menu.folder)
							{
								if (item.title.empty())
								{
									menu = item;
								}
								else
								{
									if (client == "M" && item.url[0] == '@') continue;

									++num;
								}
							}
						}
					}

					if (num > 0 && menus.insert(menu.folder).second) ms.push_back(menu);
				}
			}
		}
	}

	std::sort(ms.begin(), ms.end(), [](const MenuItem& a, const MenuItem& b){
		return a.position < b.position;
	});
	
	JsonElement arr = json.addArray("list");

	for (auto& menu : ms)
	{
		JsonElement item = arr[res++];

		item["folder"] = menu.folder;
		item["icon"] = menu.icon;
	}

	json["code"] = res;
	out << json;

	return XG_OK;
}